package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.exception.BadRequestException;
import com.hmall.common.exception.BizIllegalException;
import com.hmall.common.utils.BeanUtils;

import com.hmall.item.domain.dto.ItemDTO;
import com.hmall.item.domain.dto.OrderDetailDTO;
import com.hmall.item.domain.po.Item;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.service.IItemService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Override
    @Transactional
    public void deductStock(List<OrderDetailDTO> items) {
        for (OrderDetailDTO item : items) {
            // 查询商品当前库存
            Item currentItem = getById(item.getItemId());
            if (currentItem == null) {
                throw new BadRequestException("商品不存在");
            }

            // 检查库存是否充足
            if (currentItem.getStock() < item.getNum()) {
                throw new BizIllegalException("商品" + currentItem.getName() + "库存不足");
            }

            // 扣减库存
            int newStock = currentItem.getStock() - item.getNum();
            if (newStock < 0) {
                newStock = 0; // 防止负数
            }

            // 更新库存
            lambdaUpdate()
                    .eq(Item::getId, item.getItemId())
                    .set(Item::getStock, newStock)
                    .update();
        }
    }



    @Override
    public List<ItemDTO> queryItemByIds(Collection<Long> ids) {
        return BeanUtils.copyList(listByIds(ids), ItemDTO.class);
    }
}
